// ==UserScript==
// @name         YuQue tools
// @namespace    http://tampermonkey.net/
// @version      0.3
// @description  下载语雀文章为markdown文件
// @author       moeote
// @match        https://www.yuque.com/*
// @require      https://cdn.jsdelivr.net/npm/js-base64@3.7.2/base64.min.js
// @homepage
// @license      MIT
// @grant        none
// ==/UserScript==
(function() {
    "use strict";

    window.onload = () => {
        setTimeout(() => {
            main();
        }, 1e3);
    };

    function main() {
        console.log("TT > onload", "onload");
        // 获取视频下载链接
        var a = document.createElement("button");
        a.innerText = "导出md";
        a.style.position = "absolute";
        a.style.zIndex = 1000;
        a.style.right = 0;

        const hackUrl = "/markdown?plain=true&linebreak=false&anchor=false";
        if (!window.location.href.includes(hackUrl)) {
            const title = document.querySelectorAll("h1")[0].innerHTML;
            a.addEventListener("click", function() {
                const newWin = window.open(window.location.href + hackUrl, "_blank");
                newWin.document.title = title;

                const loop = setInterval(function() {
                    if (win.closed) {
                        clearInterval(loop);
                    } else {
                        newWin.document.title = title;
                    }
                }, 100);
            });

            document.body.prepend(a);
        } else {
            setTimeout(() => {
                var html = document.body.outerHTML;
                const fileName = window.document.title;
                console.log("TT > fileName", fileName);
                export_raw(fileName + ".md", html);

                function export_raw(name, data) {
                    var urlObject = window.URL || window.webkitURL || window;
                    var export_blob = new Blob([data]);
                    var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
                    save_link.href = urlObject.createObjectURL(export_blob);
                    save_link.download = name;
                    download_html(save_link);
                }

                function download_html(obj) {
                    var ev = document.createEvent("MouseEvents");
                    ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    obj.dispatchEvent(ev);
                }

                setTimeout(() => {
                    window.opener = null;
                    window.close();
                }, 500);
            }, 1000);
        }
    }
})();